package com.kotlin.novel.ui

import android.app.Activity
import android.content.Intent
import android.database.sqlite.SQLiteConstraintException
import android.os.Build
import android.util.Log
import android.view.View
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.novel.R
import com.kotlin.novel.adapter.ChapterAdapter
import com.kotlin.novel.appDB
import com.kotlin.novel.base.BaseActivity
import com.kotlin.novel.imageloader.ImageLoader
import com.kotlin.novel.listener.OnItemPositionClickListener
import com.kotlin.novel.listener.RVOScrollListener
import com.kotlin.novel.model.BookModel
import com.kotlin.novel.model.BookRepositoryImpl
import com.kotlin.novel.model.ChapterModel
import com.kotlin.novel.utils.HttpUtil
import com.mewlxy.readlib.Constant
import com.mewlxy.readlib.activity.NovelReadActivity
import kotlinx.android.synthetic.main.activity_book.*
import kotlinx.android.synthetic.main.title_view.*
import kotlinx.coroutines.*
import okhttp3.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit


class BookDetailActivity : BaseActivity(), View.OnClickListener, OnItemPositionClickListener<ChapterModel> {
    private val uiScope = CoroutineScope(Dispatchers.Main)
    private lateinit var chapterAdapter: ChapterAdapter
    private val chapters = ArrayList<ChapterModel>()
    private val chaptersBuffer=ArrayList<ChapterModel>()

    private val ganUrl="10.60.207.122"
    private var limit=30
    private var currentPage=0
    private var totalPageCount=0

    private var sourceLink = ""
    private var bookModel: BookModel = BookModel()

    private lateinit var rvChapter: RecyclerView

    override fun getLayoutResId(): Int {
        return R.layout.activity_book
    }

    override fun initView() {
        rvChapter=findViewById(R.id.rv_chapters)
        rvChapter.layoutManager = LinearLayoutManager(this)
    }

    override fun initData() {
        val name = intent.getStringExtra("name")
        val bookUrl = intent.getStringExtra("bookUrl")
        tv_title.text = name
        iv_title_back.setOnClickListener(this)
        tv_add_shelf.setOnClickListener(this)
        tv_read.setOnClickListener(this)
        tv_read.setOnClickListener(this)

        chapterAdapter = ChapterAdapter(this, chaptersBuffer)
        chapterAdapter.setOnItemViewClickListener(this)

        rvChapter.adapter = chapterAdapter

        val scroller: NestedScrollView = findViewById<View>(R.id.tv_loadChapter) as NestedScrollView

        scroller.setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener {
            override fun onScrollChange(v: NestedScrollView, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
                if (scrollY > oldScrollY) {
                    Log.i("", "Scroll DOWN")
                }
                if (scrollY < oldScrollY) {
                    Log.i("", "Scroll UP")
                }
                if (scrollY == 0) {
                    Log.i("", "TOP SCROLL")
                }
                if (scrollY == v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight()) {
                    loadMoreChapter(currentPage)
                }
            }
        })

        requestData(bookUrl)


    }

    private fun loadMoreChapter(page: Int){
        Log.d("总章节", "${totalPageCount}")
        Log.d("当前加载章节", "$page")
        if (totalPageCount<=page+limit){
            for (i in page+1 until totalPageCount ){
                chaptersBuffer.add(chapters[i])
            }
            currentPage=totalPageCount
        }else{
            for (i in page+1 until page+limit ){
                chaptersBuffer.add(chapters[i])
            }
            currentPage+=limit-1
        }

        setUiData(null, chaptersBuffer)
    }
    private fun requestData(bookUrl: String) = GlobalScope.launch(Dispatchers.Main) {

        val http = HttpUtil()

        chaptersBuffer.clear()
        //不能在UI线程进行请求，使用async起到后台线程，使用await获取结果
        async(Dispatchers.Default) { http.httpGET1("http://api.zhuishushenqi.com/book/${bookUrl}") }.await()
                .let {

                    val obj = JSONObject(it)

                    val coverUrl = obj.getString("cover").replace("%3A", ":").replace("%2F", "/").replace("/agent/", "")
                    val bookName = obj.getString("title")
                    val author = obj.getString("author")
                    val category = obj.getString("majorCate")
                    val status = if (obj.getString("isSerial").equals("true")) "连载中" else "已完结"
                    val desc = obj.getString("longIntro")

                    bookModel.name = bookName
                    bookModel.coverUrl = coverUrl
                    bookModel.url = bookUrl
                    bookModel.bookAuthor = author
                    bookModel.category = category
                    bookModel.status = status
                    bookModel.desc = desc

                    bookModel.chaptersUrl = "http://api.zhuishushenqi.com/mix-atoc/${bookUrl}?view=chapters"
                    bookModel.source = obj.getString("copyright")

                    Log.d("set1", "ok")

                    setUiData(bookModel, null)


                    val client = OkHttpClient().newBuilder()
                            .connectTimeout(1 * 1000, TimeUnit.MILLISECONDS)
                            .readTimeout(3 * 1000, TimeUnit.MILLISECONDS)
                            .writeTimeout(3 * 1000, TimeUnit.MILLISECONDS).build()

                    val request = Request.Builder()
                            .url("http://${ganUrl}:8000/getChapters/${bookName}/${author}")
                            .build()

                    client.newCall(request).enqueue(object : Callback {
                        //这里用的是enqueue是异步请求，可以重写Callback匿名类的方法
                        //kotlin匿名类用object：类名（）{}这里是用得lambda去了参数括号
                        override fun onResponse(call: Call, response: Response) {
                            var resText = response.body?.string()
                            var length = 0
                            try {
                                length = JSONArray(resText).length()
                            } catch (e: Exception) {
                                onFailure(call, IOException("请求失败"))
                            }

                            if (length > 0) {
                                Log.d("gan chapter url:","http://${ganUrl}:8000/getChapters/${bookName}/${author}")
                                Log.d("chapter from gan", "ok")
                                val listArray = JSONArray(resText)
                                //val chapters = ArrayList<ChapterModel>()
                                for (i in 0 until listArray.length()) {
                                    val item = listArray.getJSONObject(i)
                                    val chapterModel = ChapterModel()
                                    chapterModel.bookName = bookName
                                    chapterModel.bookUrl = bookUrl
                                    chapterModel.index = i
                                    chapterModel.name = item.getString("title")

                                    chapterModel.url = "http://${ganUrl}:8000/getContent/${bookName}/${author}/${chapterModel.name}"
                                    chapters.add(chapterModel)
                                }
                                uiScope.launch(Dispatchers.IO) {
                                    try {
                                        appDB.bookDao().delete(bookModel)
                                        appDB.chapterDao().deleteBookByBookUrl(bookUrl)
                                        appDB.bookDao().inserts(bookModel)
                                        appDB.chapterDao().inserts(*chapters.toTypedArray())

                                    } catch (e: SQLiteConstraintException) {
                                    }
                                }
                                totalPageCount = chapters.size
                                if (chapters.size <= limit) {
                                    currentPage = chapters.size
                                    chaptersBuffer.addAll(chapters)
                                } else {
                                    for (i in 0..limit) {
                                        chaptersBuffer.add(chapters[i])
                                    }
                                    currentPage = limit
                                }
                                uiScope.launch(Dispatchers.Main) { setUiData(bookModel, chaptersBuffer) }
                                //uiScope.launch(Dispatchers.Main) {setUiData(bookModel, chapters)}
                                Log.d("章节请求完成", "ok")
                            } else {
                                onFailure(call, IOException("书本为空"))
                            }
                        }

                        override fun onFailure(call: Call, e: IOException) {

                            Log.d("chapter from vip", "ok")
                            val res = http.httpGET1("http://api.zhuishushenqi.com/btoc?view=summary&book=${bookUrl}")
                            val obj1 = JSONArray(res)
                            sourceLink = obj1.getJSONObject(0).getString("_id")
                            val res2 = http.httpGET1("http://api.zhuishushenqi.com/atoc/${sourceLink}?view=chapters")
                            //val chapters = ArrayList<ChapterModel>()
                            val obj = JSONObject(res2)
                            val listArray = obj.getJSONArray("chapters")
                            for (i in 0 until listArray.length()) {
                                val item = listArray.getJSONObject(i)
                                if (item.getString("isVip") == "true")
                                    break
                                val chapterModel = ChapterModel()
                                chapterModel.bookName = bookName
                                chapterModel.bookUrl = bookUrl
                                chapterModel.index = i
                                chapterModel.name = item.getString("title")
                                val chapterUrl = item.getString("link")
                                        .replace(":", "%3A")
                                        .replace("/", "%2F")
                                        .replace("?", "%3F")
                                        .replace("=", "%3D")

                                chapterModel.url = "http://chapterup.zhuishushenqi.com/chapter/${chapterUrl}"
                                chapters.add(chapterModel)
                                //Log.d("add",chapters.last().name)
                            }
                            Log.d("set2", "ok")

                            uiScope.launch(Dispatchers.IO) {
                                try {
                                    appDB.bookDao().delete(bookModel)
                                    appDB.chapterDao().deleteBookByBookUrl(bookUrl)
                                    appDB.bookDao().inserts(bookModel)
                                    appDB.chapterDao().inserts(*chapters.toTypedArray())

                                } catch (e: SQLiteConstraintException) {
                                }
                            }
                            Log.d("章节列表url", "http://api.zhuishushenqi.com/atoc/${sourceLink}?view=chapters")
                            Log.d("章节列表", "${chapters.size}")
                            totalPageCount = chapters.size
                            if (chapters.size <= limit) {
                                currentPage = chapters.size
                                chaptersBuffer.addAll(chapters)
                            } else {
                                for (i in 0..limit) {
                                    chaptersBuffer.add(chapters[i])
                                }
                                currentPage = limit
                            }
                            uiScope.launch(Dispatchers.Main) { setUiData(bookModel, chaptersBuffer) }
                            //uiScope.launch(Dispatchers.Main) {setUiData(bookModel, chapters)}
                            Log.d("章节请求完成", "ok")
                        }
                    })
                }

/*        uiScope.launch ( Dispatchers.IO){
            appDB.bookDao().deleteAll()
            appDB.chapterDao().deleteAll()
            appDB.bookSignDao().deleteAll()
            appDB.readRecordDao().deleteAll()
            Log.d("delete all","ok")
        }*/
    }

    private fun setUiData(bookModel: BookModel?, chapterList: MutableList<ChapterModel>?) {
        if ( this.isFinishing() || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && this.isDestroyed())) {
            return
        }
        if (bookModel != null) {
            this.bookModel = bookModel
            ImageLoader.loadImage(this@BookDetailActivity, iv_cover, bookModel.coverUrl)
            tv_name.text = bookModel.name
            tv_author.text = "作者：${bookModel.bookAuthor}"
            tv_type.text = "类别：${bookModel.category}"
            tv_status.text = "状态：${bookModel.status}"

            tv_desc.text = bookModel.desc
        }

        if (chapterList != null) {
/*            chapters.clear()
            Log.d("chapter is", chapterList.last().name)
            uiScope.launch(Dispatchers.Main) {
                async(Dispatchers.Default) { chapters.addAll(chapterList) }.await()
                        .let {
                            chapterAdapter.notifyDataSetChanged()
                        }
            }*/
            chapterAdapter.notifyDataSetChanged()
        }
        Log.d("change chapter info", "ok")
    }

    private fun addToShelf(bookModel: BookModel) {
        BookRepositoryImpl.instance.saveCollBookWithAsync(bookModel.convert2BookBean())
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_title_back -> {
                finish()
            }
            R.id.tv_add_shelf -> {
                addToShelf(bookModel)
            }
            R.id.tv_read -> {
                NovelReadActivity.start(this, bookModel.convert2BookBean(), BookRepositoryImpl.instance)
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Activity.RESULT_OK) {
            val favorite = data?.getIntExtra(Constant.ResultCode.RESULT_IS_COLLECTED, 0)
            if (favorite != null) {
                bookModel.favorite = favorite
            }
        }

    }

    //点击章节进行阅读
    override fun itemClick(position: Int, t: ChapterModel) {
        Log.d("position is", "$position")
        val bookBean = bookModel.convert2BookBean()
        bookBean.specify = position
        NovelReadActivity.start(this, bookBean, BookRepositoryImpl.instance)
    }
}